/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package co.com.smart.hawk.view.impl;

import co.com.smart.hawk.controller.HawkArticulosCtrl;
import co.com.smart.hawk.controller.HawkInventarioInicialCtrl;
import co.com.smart.hawk.controller.HawkSitiosCtrl;
import co.com.smart.hawk.controller.impl.HawkArticulosCtrlImpl;
import co.com.smart.hawk.controller.impl.HawkSitiosCtrlImpl;
import co.com.smart.hawk.dto.ArticulosDTO;
import co.com.smart.hawk.dto.InventarioInicialDTO;
import co.com.smart.hawk.dto.SitiosDTO;
import co.com.smart.hawk.utilities.HawkComboBoxMgr;
import co.com.smart.hawk.utilities.HawkTableMgr;
import co.com.smart.hawk.utilities.HawkViewMgr;
import co.com.smart.hawk.utilities.Utility;
import co.com.smart.hawk.view.HawkInventarioInicioView;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.math.BigDecimal;
import java.util.List;
import javax.swing.*;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;

/**
 *
 * @author User
 */
public class HawkInventarioInicialViewImpl extends javax.swing.JInternalFrame implements HawkInventarioInicioView{

    
    private HawkInventarioInicialCtrl controller;
    private HawkComboBoxMgr<ArticulosDTO> comboMgrArticulos;
    private HawkComboBoxMgr<SitiosDTO> comboMgrSitios;
    private HawkArticulosCtrl controllerArticulos;
    private HawkSitiosCtrl controllerSitios;
    private HawkTableMgr<InventarioInicialDTO> tableMgr;
    /**
     * Creates new form HawkInventarioInicialViewImpl
     */
    public HawkInventarioInicialViewImpl(JDesktopPane desktoppane, HawkInventarioInicialCtrl hawkInventarioCtrl) {
        if (HawkViewMgr.getInstance().getObjectInstance(this.getClass()) == null) {
            try {
                this.controller = hawkInventarioCtrl;
                initComponents();
                this.initEvent();
                this.initComponentsInventarioInicio();
                java.awt.Dimension dimension = desktoppane.size();
                java.awt.Dimension ventan = this.getSize();
                this.setLocation(new java.awt.Point((dimension.width - ventan.width) / 2, (dimension.height - ventan.height) / 2));
                HawkViewMgr.getInstance().setObjectInstance(this);
            } catch (Throwable ex) {
                ex.printStackTrace();
            }
        }
        HawkViewMgr.getInstance().setObjectInstance(this);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        btnGuardar = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jPanel4 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        cbArticulo = new javax.swing.JComboBox();
        cbSitio = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        txtCantidad = new javax.swing.JTextField();
        jPanel5 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbInventarioInicial = new javax.swing.JTable();

        setClosable(true);
        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("SmartHawk-Inventario Inicial");
        setFrameIcon(new javax.swing.ImageIcon(getClass().getResource("/img/smart-jungle.png"))); // NOI18N

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));

        jLabel1.setFont(new java.awt.Font("Verdana", 1, 12)); // NOI18N
        jLabel1.setText("Inventario Inicial");

        btnGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/guardar.png"))); // NOI18N
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/limpiar.png"))); // NOI18N

        jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/consultar.png"))); // NOI18N

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(btnGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addContainerGap())
            .addComponent(btnGuardar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        jLabel2.setText("Articulo");

        jLabel3.setText("Sitio");

        cbArticulo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { " " }));

        cbSitio.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbSitioActionPerformed(evt);
            }
        });

        jLabel4.setText("Cantidad");

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addGap(18, 18, 18)
                .addComponent(cbArticulo, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(40, 40, 40)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(cbSitio, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(35, 35, 35)
                .addComponent(jLabel4)
                .addGap(26, 26, 26)
                .addComponent(txtCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(26, Short.MAX_VALUE))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3)
                    .addComponent(cbArticulo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cbSitio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4)
                    .addComponent(txtCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(69, Short.MAX_VALUE))
        );

        jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Lista Inventario Inicial", 0, 0, new java.awt.Font("Verdana", 1, 12))); // NOI18N

        tbInventarioInicial.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Articulo", "Sitio", "Cantidad", "Acción"
            }
        ));
        jScrollPane1.setViewportView(tbInventarioInicial);

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1)
                .addContainerGap())
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
                .addGap(0, 11, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(43, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cbSitioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbSitioActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_cbSitioActionPerformed

    private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed
        grabarInventarioInicio();
    }//GEN-LAST:event_btnGuardarActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnGuardar;
    private javax.swing.JComboBox cbArticulo;
    private javax.swing.JComboBox cbSitio;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tbInventarioInicial;
    private javax.swing.JTextField txtCantidad;
    // End of variables declaration//GEN-END:variables

    @Override
    public void initEvent() {
       

        this.addInternalFrameListener(new InternalFrameAdapter() {

            @Override
            public void internalFrameClosing(InternalFrameEvent e) {
                SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {

                    @Override
                    protected Void doInBackground() throws Exception {
                        return null;
                    }

                    @Override
                    protected void done() {
                        cancelarProceso();
                    }
                };
                worker.execute();
            }
        });
    }

    @Override
    public void initComponentsInventarioInicio() {
        try{
        controllerSitios = new HawkSitiosCtrlImpl();
        controllerArticulos = new HawkArticulosCtrlImpl();
        tableMgr = new HawkTableMgr<>(tbInventarioInicial);
        tableMgr.setPosition(HawkTableMgr.PositionObject.LAST);
         JLabel buscar = new JLabel(new ImageIcon(getClass().getResource("/img/search_grid.png")));
            buscar.addMouseListener(new MouseAdapter() {

                @Override
                public void mouseClicked(MouseEvent e) {
                    try {
                        InventarioInicialDTO inventarioInicialDTO = tableMgr.getSelectObject();
                       /* txtscsitio.setText(sitios.getScsitios().toString());
                        txtCodigo.setText(sitios.getCositios());
                        txtDescripcionSitio.setText(sitios.getDssitios());*/
                    } catch (Throwable ex) {
                        ex.printStackTrace(System.err);
                    }
                }
            });
            tableMgr.addNewValueColumn(buscar);
        listarSitios();
        listarArticulos();
        listarInventarioinicial();
        }catch(Throwable ex) {
            ex.printStackTrace(System.err);
        }
    }

    @Override
    public void grabarInventarioInicio() {
        if (validarCampos()) {
            try {
                InventarioInicialDTO sendObject = new InventarioInicialDTO();
                ArticulosDTO articulosDTO = new ArticulosDTO();
                SitiosDTO sitiosDTO = new SitiosDTO();

                
                articulosDTO =comboMgrArticulos.getSelectedItem();
                sitiosDTO= comboMgrSitios.getSelectedItem();
                sendObject.setArticulos(articulosDTO);
                sendObject.setSitios(sitiosDTO);
                sendObject.setNmcantidad(new Double(txtCantidad.getText()));

                controller.grabarInventarioInicial(new Utility.CallBackSmartHawk<InventarioInicialDTO>() {

                    @Override
                    public void endProcess(InventarioInicialDTO object) {
                        JOptionPane.showMessageDialog(HawkInventarioInicialViewImpl.this, object.getDsmensaje(), "Información", JOptionPane.INFORMATION_MESSAGE);
                        // limpiarFormulario();
                    }
                }, sendObject);
                listarInventarioinicial();
            } catch (Throwable thr) {
                JOptionPane.showMessageDialog(this, "Error almacenado el inventario inicial: \n" + thr.getMessage(), "Error procesando", JOptionPane.ERROR_MESSAGE);
                return;
            }

        }
    }
    
     /**
     * valida los campos obligatorios para la vista
     *
     * @return
     */
    private boolean validarCampos() {
        boolean flag = true;

        if (this.comboMgrArticulos.getSelectedItem() == null && flag) {
            JOptionPane.showMessageDialog(this, "El artículo es obligatorio", "Validación", JOptionPane.WARNING_MESSAGE);
            flag = false;
        }
        
        if (this.comboMgrSitios.getSelectedItem() == null && flag) {
            JOptionPane.showMessageDialog(this, "El sitio es obligatorio", "Validación", JOptionPane.WARNING_MESSAGE);
            flag = false;
        }

        if (txtCantidad == null || "".equals(txtCantidad.getText()) && flag) {
            JOptionPane.showMessageDialog(this, "La cantidad es obligatoria", "Validación", JOptionPane.WARNING_MESSAGE);
            flag = false;
            txtCantidad.grabFocus();
        }

        return flag;
    }

    @Override
    public void limpiarFormulario() {        
            txtCantidad.setText("0");
            comboMgrArticulos.refresh();
            comboMgrSitios.refresh();
    }

    @Override
    public void cancelarProceso() {
       
        int message = JOptionPane.showConfirmDialog(this, "Está seguro que desea salir?", "Salir", JOptionPane.YES_NO_OPTION);
        if (message == JOptionPane.YES_OPTION) {
            HawkViewMgr.getInstance().removeObjectInstance(this.getClass());
            System.gc();
            this.dispose();
        }
    }
    
    
    @Override
    public void listarArticulos() {
        ArticulosDTO articulosDTO = new ArticulosDTO();
        
        try{
            controllerArticulos.ListarArticulos(new Utility.CallBackSmartHawk<List<ArticulosDTO>>() {
            @Override
            public void endProcess(List<ArticulosDTO> object) {
                
                    comboMgrArticulos = new HawkComboBoxMgr<>(cbArticulo);
                    comboMgrArticulos.setEmptyValue(null);
                    comboMgrArticulos.setData(object);
                }
            }, articulosDTO);
        }catch(Throwable thr){
            JOptionPane.showMessageDialog(this, "Error cargando los articulos :\n" + thr.getMessage(), "Error carga inicial", JOptionPane.ERROR_MESSAGE);
        }
    }
    
     @Override
    public void listarSitios() {
        
        try{
            controllerSitios.consultarSitios(new Utility.CallBackSmartHawk<List<SitiosDTO>>() {
            @Override
            public void endProcess(List<SitiosDTO> object) {
                
                    comboMgrSitios = new HawkComboBoxMgr<>(cbSitio);
                    comboMgrSitios.setEmptyValue(null);
                    comboMgrSitios.setData(object);
                }
            });
        }catch(Throwable thr){
            JOptionPane.showMessageDialog(this, "Error cargando los sitios :\n" + thr.getMessage(), "Error carga inicial", JOptionPane.ERROR_MESSAGE);
        }
    }
     
      @Override
    public void listarInventarioinicial()  throws Throwable {
         InventarioInicialDTO filtros = new InventarioInicialDTO(); 
        controller.listarInventarioinicial(new Utility.CallBackSmartHawk<List<InventarioInicialDTO>>() {

            @Override
            public void endProcess(List<InventarioInicialDTO> object) {
                try {
                    tableMgr.clearAll();
                    tableMgr.setData(object);
                } catch (Throwable ex) {
                    ex.printStackTrace(System.err);
                    JOptionPane.showMessageDialog(HawkInventarioInicialViewImpl.this, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
                }

            }
        },filtros);
    }

}
